<!-- 上传头像 -->
<template lang="html">
	<mu-dialog title="上传头像" :open.sync="open" @close="closeAlertDialog" :esc-press-close="false" :overlay-close="false"
	 width="600">
		<div class="rz-picter">
			<img :src="avatar" class="img-avatar">
			<input type="file" name="avatar" id="uppic" accept="image/gif,image/jpeg,image/jpg,image/png" @change="changeImage($event)"
			 ref="avatarInput" class="uppic">
		</div>
		<div style="text-align: center;">
			<mu-button color="primary" @click="uploadPhoto">确认</mu-button>
			<mu-button @click="closeAlertDialog">取消</mu-button>
		</div>
	</mu-dialog>

</template>

<script type="text/javascript">
	export default {
		// 不要忘记了 name 属性
		name: 'uploadPhoto',
		// 组合其它组件
		extends: {},
		// 组件属性、变量
		props: { // 按字母顺序
			openPhoto: {
				type: Boolean,
				default: false
			}
		},
		// 变量
		data() {
			return {
				avatar: require('../assets/jia.png'),
				open: this.openPhoto,
				file:''
			}
		},
		computed: {

		},
		// 使用其它组件
		components: {},
		// 方法
		watch: {
			openPhoto: {
				//注意：当观察的数据为对象或数组时，curVal和oldVal是相等的，因为这两个形参指向的是同一个数据对象
				handler(curVal, oldVal) {
					this.open = this.openPhoto
				},
				deep: true
			}
		},
		methods: {
			changeImage(e) {
				var file = e.target.files[0]
				this.file=file;
				if (file != undefined) {
					var reader = new FileReader()
					let self = this
					reader.readAsDataURL(file)
					reader.onload = function(e) {
						self.avatar = this.result
					}
				} else {
					this.file=undefined
					this.avatar = require('../assets/jia.png');
				}

			},
			uploadPhoto() {
				let self = this
				if (this.file == undefined) {
					self.$toast.error('请上传图片');
					return;
				}


				var formdata = new FormData();
				formdata.append("photo", this.file);
				self.$ajax({
						method: "post",
						url: "/user/upload",
						data: formdata
					})
					.then(function(res) {
						if (res.data.code == 200) {
							self.$toast.success('上传成功！');
							localStorage.setItem('user', JSON.stringify(res.data.data));
							self.$emit('getUser', res.data.data);
						}
					})
					.catch(function(err) {
						console.log(err);

					});

				self.closeAlertDialog();
			},
			closeAlertDialog() {
				this.avatar = require('../assets/jia.png');
				this.$emit('openPhoto', false);

			},
		},
		// 生命周期函数
		beforeCreate() {},
		mounted() {},
	};
</script>

<style scoped>
	.rz-picter {
		height: 110px;
		width: 110px;
		margin: 0.3rem auto;
		border: 0.01rem solid #ededed;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.uppic {
		height: 3rem;
		width: 6rem;
		margin: 0 auto;
		opacity: 0;
		z-index: 99999;
	}

	.img-avatar {
		height: 100px;
		width: 100px;
		position: absolute;
	}
</style>
